using System.Text.Json;
using System.Text.Json.Serialization;
using Vin.Tool.Core.BasicTypeCategory;
using Vin.Tool.Core.DateTimeCategory;
using Vin.Tool.Core.JsonCategory.TimeFormat;

namespace Vin.Tool.Core.JsonCategory.Converters;

public class LongTimeToStringConverter<T> : JsonConverter<long> where T : ITimeFormat, new()
{
    private readonly T _timeFormat;

    public LongTimeToStringConverter()
    {
        _timeFormat = new T();
    }

    public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String)
        {
            return reader.GetString().ToDateTime().ToTimestamp(false);
        }
        else if (reader.TokenType == JsonTokenType.Number)
        {
            return reader.GetInt64();
        }

        throw new JsonException($"Unable to parse {typeToConvert.Name} from JSON.");
    }

    public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
    {
        if (value > 0)
        {
            // writer.WriteStringValue(value.ToString().Length == 10
            //     ? TimestampTool.ConvertToDateTimeSeconds(value).ToString("yyyy-MM-dd HH:mm:ss")
            //     : TimestampTool.ConvertToDateTime(value).ToString("yyyy-MM-dd HH:mm:ss"));
            writer.WriteStringValue(value.ToString().Length == 10
                ? TimestampTool.ConvertToDateTimeSeconds(value).ToString(_timeFormat.Format())
                : TimestampTool.ConvertToDateTime(value).ToString(_timeFormat.Format()));
        }
        else
        {
            writer.WriteStringValue("");
        }
    }
}

public class LongTimeToStringConverter : LongTimeToStringConverter<YYYYMMSSHHmmssFormat>;

// public class LongTimeToStringConverter : JsonConverter<long>
// {
//     public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
//     {
//         if (reader.TokenType == JsonTokenType.String)
//         {
//             return reader.GetString().ToDateTime().ToTimestamp(false);
//         }
//         else if (reader.TokenType == JsonTokenType.Number)
//         {
//             return reader.GetInt64();
//         }
//
//         throw new JsonException($"Unable to parse {typeToConvert.Name} from JSON.");
//     }
//
//     public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
//     {
//         if (value > 0)
//         {
//             writer.WriteStringValue(value.ToString().Length == 10
//                 ? TimestampTool.ConvertToDateTimeSeconds(value).ToString("yyyy-MM-dd HH:mm:ss")
//                 : TimestampTool.ConvertToDateTime(value).ToString("yyyy-MM-dd HH:mm:ss"));
//         }
//         else
//         {
//             writer.WriteStringValue("");
//         }
//     }
// }